package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
//        resp.setCharacterEncoding("utf8");
        resp.setContentType("text/html; charset=utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if (username == null || "".equals(username) || password == null || "".equals(password)) {
            // 失败
            String html = "<h3> 登录失败, 缺少用户名或密码 </h3>";
            resp.getWriter().write(html);
            return;
        }
        UserDao userDao = new UserDao();
        User user = userDao.selectByUsername(username);
        if (user == null || !password.equals(user.getPassword())) {
            String html = "<h3> 登录失败, 用户名或密码错误 </h3>";
            resp.getWriter().write(html);
            return;
        }

        // 用户名密码验证通过, 登录成功, 接下来创建回话, 使用该会话保存用户信息
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);

        // 重定向
        resp.sendRedirect("blog_list.html");
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        // 获取用户的登录状态

        HttpSession session = req.getSession(false);
        if (session == null) {
            User user = new User();
            String respJson = objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            user = new User();
            String respJson = objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
            return;
        }

        // user 不为空, 直接返回即可
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
